var express = require('express');
var router = express.Router();
var db = require('../../data');

/* GET home page. */
router.get('/', function(req, res, next) {
    var session = req.session;
    var data = db.model;


    if(!session.user || !session.user.login){
        res.redirect('/admin/login');
    }else{

        data.basicFacts.findOne(function(err, docs){
            if(err)
                return next();

            var returnData = {
                path: 'adminUser',
                basicFacts : docs,
                user : session.user
            };

            data.adminUser.find({},function(err, docs){
                returnData.data = docs;
                console.log(returnData);
                res.render('admin/adminUser', returnData);
            }).sort({auid: -1});
        });

    };
});

router.post('/add', function(req, res, next){

    var user = db.model.adminUser;
    var sha1 = require('crypto').createHash('sha1');
    sha1.update(req.body.pass);
    req.body.pass = sha1.digest('hex');

    user.find({user: req.body.user}, function(err, docs){
        if(err){
            res.send({status: 2});
        }else{
            if(docs.length)
                res.send({status: 3, msg: "该用户已存在"});
            else{
                var addUser = new user(req.body);
                var st = addUser.save(function(err, c){
                    if(err)
                        res.send({status: 1});
                    else{
                        res.send({status: 0, auid: c.auid});
                    }
                });
            }
        }
    });
});

module.exports = router;
